/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlador;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import Modelo.Acceso;
import Modelo.Usuario;
import java.awt.HeadlessException;
import javax.swing.JOptionPane;

/**
 *
 * @author diegomanguia
 */
public class ControlUsuario extends Conexion {

    public ControlUsuario() {
    }

    public boolean validadorDeCedula(String cedula) {
        boolean cedulaCorrecta = false;

        try {

            if (cedula.length() == 10) // ConstantesApp.LongitudCedula
            {
                int tercerDigito = Integer.parseInt(cedula.substring(2, 3));
                if (tercerDigito < 6) {
// Coeficientes de validación cédula
// El decimo digito se lo considera dígito verificador
                    int[] coefValCedula = {2, 1, 2, 1, 2, 1, 2, 1, 2};
                    int verificador = Integer.parseInt(cedula.substring(9, 10));
                    int suma = 0;
                    int digito = 0;
                    for (int i = 0; i < (cedula.length() - 1); i++) {
                        digito = Integer.parseInt(cedula.substring(i, i + 1)) * coefValCedula[i];
                        suma += ((digito % 10) + (digito / 10));
                    }

                    if ((suma % 10 == 0) && (suma % 10 == verificador)) {
                        cedulaCorrecta = true;
                    } else if ((10 - (suma % 10)) == verificador) {
                        cedulaCorrecta = true;
                    } else {
                        cedulaCorrecta = false;
                    }
                } else {
                    cedulaCorrecta = false;
                }
            } else {
                cedulaCorrecta = false;
            }
        } catch (NumberFormatException nfe) {
            cedulaCorrecta = false;
        } catch (Exception err) {
            System.out.println("Una excepcion ocurrio en el proceso de validadcion");
            cedulaCorrecta = false;
        }

        if (!cedulaCorrecta) {
            System.out.println("La Cédula ingresada es Incorrecta");
        }
        return cedulaCorrecta;
    }

    public ArrayList<Acceso> listar() {
        ArrayList listauser = new ArrayList();
        String sql = "Select * from usuario";
        Connection cn = null;
        try {
            cn = conectar();
        } catch (SQLException ex) {
            Logger.getLogger(ControlProdServ.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            PreparedStatement ps = cn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Acceso obj = new Acceso(rs.getString("USU_CEDULA"), rs.getString("USU_CONTRASENA"));
                listauser.add(obj);
            }
            desconectar(cn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return listauser;

    }

    public void insertar(String ci, String nombre, String apellido, String pass, String correo, String telf, Boolean priv) {
        ArrayList listauser = new ArrayList();
        String sql = "Select * from usuario";
        Connection cn = null;
        try {
            cn = conectar();
        } catch (SQLException ex) {
            ex.printStackTrace();
            Logger.getLogger(ControlProdServ.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex){
            ex.printStackTrace();
        }

        try {
            if (cn.getAutoCommit()) {
                cn.setAutoCommit(false);
            }
            PreparedStatement ps = cn.prepareStatement("insert into usuario(usu_cedula,"
                    + " usu_nombre, usu_apellido,usu_contrasena,usu_correo,usu_telefono,"
                    + " usu_administrador)"
                    + " values (?,?,?,?,?,?,?) ");
            ps.setString(1, ci);
            ps.setString(2, nombre);
            ps.setString(3, apellido);
            ps.setString(4, pass);
            ps.setString(5, correo);
            ps.setString(6, telf);
            ps.setBoolean(7, priv);

            int a = ps.executeUpdate();

            if (a >= 1) {
                JOptionPane.showMessageDialog(null, "Usuario Registrado Correctamente");
                cn.commit();
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Usuario ya registrado.");
        } catch (Exception ex) {
            //Logger.getLogger(PryJDBC.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
            deshacer(cn);
        }
    }

    public void actualizar(String ci, String nombre, String apellido, String pass, String correo, String telf, Boolean priv) {

        Connection cn = null;
        try {
            cn = conectar();
        } catch (SQLException ex) {
            Logger.getLogger(ControlProdServ.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            if (cn.getAutoCommit()) {
                cn.setAutoCommit(false);
            }

            PreparedStatement ps = cn.prepareStatement("update  usuario SET  usu_nombre=?, "
                    + "usu_apellido=?,usu_contrasena=?,usu_correo=?,usu_telefono=?, "
                    + "usu_administrador=? where usu_cedula=?");

            ps.setString(1, nombre);
            ps.setString(2, apellido);
            ps.setString(3, pass);
            ps.setString(4, correo);
            ps.setString(5, telf);
            ps.setBoolean(6, priv);
            ps.setString(7, ci);

            boolean a = ps.execute();

            if (a == true) {
                JOptionPane.showMessageDialog(null, "Usuario Actualizado Correctamente");
                cn.commit();
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Error al actualizar usuario.");
        } catch (Exception ex) {
            //Logger.getLogger(PryJDBC.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
            deshacer(cn);
        }
    }

    public ArrayList<Usuario> listarcompleto() throws SQLException {

        ArrayList<Usuario> lista = new ArrayList<Usuario>();

        Connection cn = conectar();

        Usuario obj;

        PreparedStatement ps = cn.prepareStatement("Select * from usuario");
        ResultSet rs = ps.executeQuery();

        while (rs.next()) {
            obj = new Usuario();
            obj.setCi(rs.getString("usu_cedula"));
            obj.setNombre(rs.getString("usu_nombre"));
            obj.setApellido(rs.getString("usu_apellido"));
            obj.setPass(rs.getString("usu_contrasena"));
            obj.setCorreo(rs.getString("usu_correo"));
            obj.setTelefono(rs.getString("usu_telefono"));
            obj.setAdmin(rs.getBoolean("usu_administrador"));
            lista.add(obj);
        }

        return lista;
    }

    public void eliminar(String cedula) throws SQLException {
        String sql = "Select * from usuario";
        Connection cn = conectar();
        PreparedStatement ps = cn.prepareStatement("Delete from usuario where usu_cedula=?");
        ps.setString(1, cedula);
        int num = ps.executeUpdate();
        if (num != 0) {
            JOptionPane.showMessageDialog(null, "eliminado");
        }
    }

    public Usuario buscarUsuario(String ci) {
        Usuario user = null;
        try {
            Connection cn = conectar();

            Usuario obj;

            PreparedStatement ps = cn.prepareStatement("Select * from usuario WHERE usu_cedula=?");
            ps.setString(1, ci);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                obj = new Usuario();
                obj.setCi(rs.getString("usu_cedula"));
                obj.setNombre(rs.getString("usu_nombre"));
                obj.setApellido(rs.getString("usu_apellido"));
                obj.setPass(rs.getString("usu_contrasena"));
                obj.setCorreo(rs.getString("usu_correo"));
                obj.setTelefono(rs.getString("usu_telefono"));
                obj.setAdmin(rs.getBoolean("usu_administrador"));
                user = obj;
            }

        } catch (SQLException err) {
            JOptionPane.showMessageDialog(null, "Error en busqueda" + err.getMessage());
        } catch (Exception ex) {
        }

        return user;
    }

    public int existenAdmin() {
        //boolean a = true;
        int num = -1;
        try {
            String sql = "SELECT count(*) FROM usuario "
                    + "WHERE usu_administrador IS TRUE";
            Connection cn = conectar();
            PreparedStatement ps = cn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                num = rs.getInt(1);
                System.out.println("count=" + num);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            //a=false;
        }

        return num;
    }
}
